<template>
  <CommonDialog
    :visible.sync="dialogVisible"
    :title="$t('home.dialog.login.title')"
    :buttons="buttons"
    @button-click="handleButtonAction"
    @close="handleClose">
    <div class="text-center">
      <!-- 第一步：邮箱输入 -->
      <div v-if="loginStep === 1">
        <p class="text-sm text-gray-600 mb-6">{{ $t("home.dialog.login.registerDesc") }}</p>
        <!-- 邮箱输入框 -->
        <div class="mb-4">
          <input
            v-model="email"
            type="email"
            :placeholder="$t('home.dialog.login.codePlaceholder')"
            class="w-full h-12 px-4 border border-gray-200 rounded-lg text-sm" />
        </div>
      </div>

      <!-- 第二步：验证码或密码 -->
      <div v-if="loginStep === 2">
        <!-- 验证码登录 -->
        <div v-if="loginType === 'code'">
          <p class="text-sm text-gray-600 mb-4">
            {{ $t("home.dialog.login.codeDesc") }}
            <span class="text-blue-500">{{ email || "your@email.com" }}</span>
            {{ $t("home.dialog.login.codeDesc2") }}
          </p>

          <!-- 验证码输入框 -->
          <div class="flex justify-center space-x-2 mb-4">
            <input
              v-for="i in 4"
              :key="i"
              :ref="`codeInput${i - 1}`"
              v-model="verificationCode[i - 1]"
              type="text"
              maxlength="1"
              class="w-12 h-12 border border-gray-300 rounded text-center text-lg"
              @input="handleCodeInput($event, i - 1)"
              @keydown="handleKeyDown($event, i - 1)" />
          </div>

          <p class="text-xs text-gray-400 mb-4">
            <van-icon name="warning-o" size="12" class="mr-1" />
            {{ $t("home.dialog.login.codeTip") }}
          </p>
        </div>

        <!-- 密码登录 -->
        <div v-else>
          <div class="mb-4">
            <input
              v-model="password"
              type="password"
              :placeholder="$t('home.dialog.login.passwordPlaceholder')"
              class="w-full h-12 px-4 border border-gray-200 rounded-lg text-sm" />
          </div>
        </div>
      </div>
    </div>
  </CommonDialog>
</template>

<script>
import { sendCode, checkPwd, codeLogin, passwordLogin } from "@/apis/login"
import { mapActions } from "vuex"
export default {
  name: "LoginDialog",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      email: "",
      password: "",
      loginStep: 1,
      loginType: "code", // 'code' or 'password'
      verificationCode: ["", "", "", "",],
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(value) {
        this.$emit("update:visible", value)
      },
    },
    // 第一步按钮：下一步
    registerButtons() {
      return [
        {
          text: this.$t("home.buttons.next"),
          type: "primary",
          action: "next",
        },
      ]
    },
    // 验证码登录按钮
    loginButtonsCode() {
      return [
        {
          text: this.$t("home.buttons.resend"),
          type: "secondary",
          action: "resend",
        },
        {
          text: this.$t("home.buttons.login"),
          type: "primary",
          action: "login",
        },
      ]
    },
    // 密码登录按钮
    loginButtonsPassword() {
      return [
        {
          text: this.$t("home.buttons.login"),
          type: "primary",
          action: "login",
        },
      ]
    },
    // 当前步骤的按钮配置
    buttons() {
      if (this.loginStep === 2) {
        if (this.loginType === "code") {
          return this.loginButtonsCode
        } else {
          return this.loginButtonsPassword
        }
      } else {
        return this.registerButtons
      }
    },
  },
  methods: {
    ...mapActions({
      login: "auth/login",
    }),
    // 处理按钮点击事件
    async handleButtonAction({ action }) {
      console.log("登录操作:", action, "邮箱:", this.email)

      // 输入邮箱 下一步
      if (action === "next") {
        // 进入下一步登录流程
        // this.$emit('step-change', { step: 2, email: this.email })
        if(this.email === '') {
          this.$toast(this.$t("home.dialog.login.codePlaceholder"))
          return
        }
        const res = await checkPwd({ email: this.email })
        this.loginStep = 2
        if (!res.data) {
          this.loginType = "code"
          await sendCode({ email: this.email })
        } else {
          this.loginType = "password"
        }
      } else if (action === "login") {
        // 执行登录逻辑
        const loginData = { email: this.email }

        if (this.loginType === "code") {
          loginData.code = this.verificationCode.join("")
        } else {
          loginData.password = this.password
        }

        if (this.loginType === "code") {
          const res = await codeLogin(loginData)
          this.handleLogin(res)
        } else {
          const res = await passwordLogin(loginData)
          this.handleLogin(res)
        }
      } else if (action === "resend") {
        await sendCode({ email: this.email })
      }
    },
    handleLogin(res) {
      this.handleClose()
      this.login({
        token: res.data.accessToken,
        userInfo: {
          email: this.email,
        },
      })
    },
    // 验证码输入处理
    handleCodeInput(event, index) {
      const value = event.target.value
      if (value && index < 3) {
        // 自动跳转到下一个输入框
        const nextInput = event.target.parentNode.children[index + 1]
        if (nextInput) {
          nextInput.focus()
        }
      }
    },

    // 处理键盘按键事件
    handleKeyDown(event, index) {
      // 检测删除键（Backspace键码为8，Delete键码为46）
      if (event.keyCode === 8 || event.key === 'Backspace') {
        // 如果当前输入框有内容，先清空当前输入框
        if (this.verificationCode[index] !== '') {
          // 阻止默认删除行为
          event.preventDefault()
          // 使用Vue.set确保响应式更新
          this.$set(this.verificationCode, index, '')
        } 
        // 如果当前输入框为空且不是第一个输入框，跳转到前一个
        else if (index > 0) {
          // 阻止默认删除行为
          event.preventDefault()
          // 将焦点移动到前一个输入框
          const prevInput = event.target.parentNode.children[index - 1]
          if (prevInput) {
            prevInput.focus()
            // 清空前一个输入框的内容
            this.$set(this.verificationCode, index - 1, '')
          }
        }
      }
      // 处理左右箭头键导航
      else if (event.keyCode === 37 || event.key === 'ArrowLeft') {
        // 左箭头键，移动到前一个输入框
        if (index > 0) {
          event.preventDefault()
          const prevInput = event.target.parentNode.children[index - 1]
          if (prevInput) {
            prevInput.focus()
          }
        }
      }
      else if (event.keyCode === 39 || event.key === 'ArrowRight') {
        // 右箭头键，移动到下一个输入框
        if (index < 3) {
          event.preventDefault()
          const nextInput = event.target.parentNode.children[index + 1]
          if (nextInput) {
            nextInput.focus()
          }
        }
      }
    },

    // 弹框关闭处理
    handleClose() {
      this.resetForm()
      this.$emit("close")
    },

    // 重置表单
    resetForm() {
      this.loginStep = 1
      this.email = ""
      this.password = ""
      this.verificationCode = ["", "", "", ""]
      this.loginType = "code"
    },

    // 切换登录方式
    switchLoginType(type) {
      this.loginType = type
    },
  },
  watch: {
    visible(newVal) {
      if (!newVal) {
        // 弹框关闭时重置表单
        this.resetForm()
      }
    },
  },
}
</script>

<style scoped>
/* 验证码输入框样式 */
input:focus {
  outline: none;
  border-color: #ff7a00;
  box-shadow: 0 0 0 2px rgba(255, 118, 0, 0.2);
}
</style>
